package com.wocai.jrt.orgadmin.product.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.DoubleEditor;
import com.vteba.web.editer.IntEditor;
import com.vteba.web.editer.LongEditor;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.model.ProductRelated;
import com.wocai.jrt.orgadmin.product.service.spi.ProductRelatedService;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 产品的相关产品控制器
 * 
 * @author yinlei
 * @date 2015-8-13 16:43:27
 */
@Controller
@RequestMapping("/productRelated")
public class ProductRelatedAction extends GenericAction<ProductRelated> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductRelatedAction.class);

	@Inject
	private ProductRelatedService productRelatedServiceImpl;

	@Inject
	private ProductService productServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(int.class, new IntEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 查看产品详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 产品详情页
	 */
	@ResponseBody
	@RequestMapping("/list/{productId}")
	public JsonBean list(@PathVariable("productId") String productId) {
		JsonBean jsonBean = new JsonBean();
		try {
			Map<String, Object> maps = new HashMap<String, Object>();
			Product product = productServiceImpl.get(productId);
			maps.put("product", product);// 将model放入视图中，供页面视图使用

			Product productParam = new Product();
			String orgId = UserUtils.getUser().getOrgId();
			productParam.setOrgId(orgId);
			List<Product> productList = productServiceImpl.pagedList(productParam);
			productParam.setId(productId);
			List<Product> relatedProductList = productServiceImpl.relatedPagedList(productParam);
			List<Product> needRemoveList = new ArrayList<Product>();
			if (null != productList && null != relatedProductList) {
				for (int i = 0; i < relatedProductList.size(); i++) {
					Product rp = relatedProductList.get(i);
					for (int j = 0; j < productList.size(); j++) {
						Product p = productList.get(j);
						if (p.getId().equals(rp.getId())) {
							needRemoveList.add(p);
							break;
						}
					}
				}

				for (int j = 0; j < productList.size(); j++) {
					Product p = productList.get(j);
					if (p.getId().equals(productId)) {
						needRemoveList.add(p);
						break;
					}
				}
			}

			productList.removeAll(needRemoveList);

			maps.put("productList", productList);
			maps.put("relatedProductList", relatedProductList);
			maps.put("productId", productId);
			jsonBean.setCode(1);
			jsonBean.setData(maps);
			jsonBean.setMessage(SUCCESS);
		} catch (Exception e) {
			LOGGER.error("fetch related list error, msg = [{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("fetch related list error");
		}

		return jsonBean;
	}
	
	@RequestMapping("/relatedList/{productId}")
	public String relatedList(@PathVariable("productId") String productId,Map<String, Object> maps) {
			Product product = productServiceImpl.get(productId);
			maps.put("product", product);// 将model放入视图中，供页面视图使用

			Product productParam = new Product();
			String orgId = UserUtils.getUser().getOrgId();
			productParam.setOrgId(orgId);
			List<Product> productList = productServiceImpl.pagedList(productParam);
			productParam.setId(productId);
			List<Product> relatedProductList = productServiceImpl.relatedPagedList(productParam);
			List<Product> needRemoveList = new ArrayList<Product>();
			if (null != productList && null != relatedProductList) {
				for (int i = 0; i < relatedProductList.size(); i++) {
					Product rp = relatedProductList.get(i);
					for (int j = 0; j < productList.size(); j++) {
						Product p = productList.get(j);
						if (p.getId().equals(rp.getId())) {
							needRemoveList.add(p);
							break;
						}
					}
				}

				for (int j = 0; j < productList.size(); j++) {
					Product p = productList.get(j);
					if (p.getId().equals(productId)) {
						needRemoveList.add(p);
						break;
					}
				}
			}

			productList.removeAll(needRemoveList);

			maps.put("productList", productList);
			maps.put("relatedProductList", relatedProductList);
			maps.put("productId", productId);

		return "product/ralatedProduct";
	}

	/**
	 * 根据Id获得产品的相关产品实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 产品的相关产品实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public ProductRelated get(String id) {
		ProductRelated model = null;
		try {
			model = productRelatedServiceImpl.get(id);
		} catch (Exception e) {
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
		}
		return model;
	}

	/**
	 * 跳转到新增页面
	 * 
	 * @return 新增页面逻辑视图
	 */
	@RequestMapping("/add")
	public String add() {
		return "productRelated/add";
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/save")
	public JsonBean save(String productId, String relatedIds) {
		JsonBean bean = new JsonBean();
		try {

			ProductRelated prParam = new ProductRelated();
			prParam.setProductId(productId);
			productRelatedServiceImpl.deleteBulks(prParam);

			if (null != relatedIds) {
				String[] relatedIdsArr = relatedIds.split(",");
				for (String refProductId : relatedIdsArr) {
					ProductRelated record = new ProductRelated();
					record.setId(ObjectId.get().toString());
					record.setProductId(productId);
					record.setRefProductId(refProductId);
					record.setOrgId(UserUtils.getUser().getOrgId());
					productRelatedServiceImpl.save(record);
				}
			}

			bean.setCode(1);
			bean.setMessage(SUCCESS);
			return bean;
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
			return bean;
		}

	}

	/**
	 * 查看产品的相关产品详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 产品的相关产品详情页
	 */
	@RequestMapping("/detail")
	public String detail(ProductRelated model, Map<String, Object> maps) {
		try {
			model = productRelatedServiceImpl.get(model.getId());
			maps.put("model", model);// 将model放入视图中，供页面视图使用
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "productRelated/detail";
	}

	/**
	 * 跳转到编辑信息页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@RequestMapping("/edit")
	public String edit(ProductRelated model, Map<String, Object> maps) {
		model = productRelatedServiceImpl.get(model.getId());
		maps.put("model", model);
		return "productRelated/edit";
	}

	/**
	 * 更新产品的相关产品信息
	 * 
	 * @param model
	 *            要更新的产品的相关产品信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(ProductRelated model) {
		JsonBean bean = new JsonBean();
		try {
			int result = productRelatedServiceImpl.updateById(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 删除产品的相关产品信息
	 * 
	 * @param id
	 *            要删除的产品的相关产品ID
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(String id) {
		JsonBean bean = new JsonBean();
		try {
			int result = productRelatedServiceImpl.deleteById(id);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("delete record success, id=[{}].", id);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("delete record error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}
}
